<template>
  <div class="component page">
    <div class="container-center">
      <div class="over-hidden">
        <router-link
          class="btn btn-default pull-right icon icon-arrowsleftline mt-lg"
          :to="getMicroRoute('/tools')"
        >
          返回列表</router-link>
        <h2 class="text-left">雪碧图</h2>
      </div>
      <div class="form-group">
        <label class="form-label"><strong>排列方式</strong></label>
        <div class="form-radio">
          <label><input name="radio" type="radio" value="vertical" v-model="config.dir">竖向</label>
          <label><input name="radio" type="radio" value="horizon" v-model="config.dir">横向</label>
          <!--<label><input name="radio" type="radio" value="tree" v-model="config.dir">树状</label>-->
        </div>
      </div>
      <div class="mt-lg">
        <button id="btn_save" class="btn btn-default pull-right">保存雪碧图</button>
        <div class="form-group">
          <label class="form-label"><strong>拖拽所有图标至画布中</strong></label>
        </div>
        <div class="container-canvas">
          <canvas id="canvas"></canvas>
        </div>
      </div>
      <div class="over-hidden">
        <div class="container-output">
          <div class="col-xs-6 row-cell">
            <h3>CSS</h3>
          </div>
          <div class="col-xs-6 row-cell">
            <h3>LESS</h3>
          </div>
          <div>
            <div class="col-xs-12 row-cell">
              <label class="form-label"><strong>图标公用样式</strong></label>
            </div>
            <div class="col-xs-6 row-cell">
              <textarea class="form-textarea css-0" rows="12"></textarea>
            </div>
            <div class="col-xs-6 row-cell">
              <textarea class="form-textarea less-0" rows="12"></textarea>
            </div>
            <div class="col-xs-12 row-cell">
              <label class="form-label"><strong>背景图模式</strong></label>
            </div>
            <div class="col-xs-6 row-cell">
              <textarea class="form-textarea css-1" rows="12"></textarea>
            </div>
            <div class="col-xs-6 row-cell">
              <textarea class="form-textarea less-1" rows="12"></textarea>
            </div>
            <div class="col-xs-12 row-cell">
              <label class="form-label"><strong>伪类模式</strong></label>
            </div>
            <div class="col-xs-6 row-cell">
              <textarea class="form-textarea css-2" rows="12"></textarea>
            </div>
            <div class="col-xs-6 row-cell">
              <textarea class="form-textarea less-2" rows="12"></textarea>
            </div>
            <div class="col-xs-12 row-cell">
              <label class="form-label"><strong>伪类模式完整</strong></label>
            </div>
            <div class="col-xs-6 row-cell">
              <textarea class="form-textarea css-3" rows="12"></textarea>
            </div>
            <div class="col-xs-6 row-cell">
              <textarea class="form-textarea less-3" rows="12"></textarea>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { imager } from '@daelui/dogjs/dist/components'

/* JSON转换 */
export default {
  data () {
    return {
      config: {
        dir: 'vertical', // 排列形式
        prefix: '', // 前缀
        gapWidth: 2 // 间隔距离
      }
    }
  },

  methods: {
    /**
     * @description 初始化
     */
    init () {
      var canvasEl = (this.canvasEl = document.querySelector('#canvas'))
      this.ctx = canvasEl.getContext('2d')

      // 设置默认宽高
      canvasEl.width = 600
      canvasEl.height = 400
      var imageList = (this.imageList = [])
      var me = this

      /* ***事件*** */
      canvasEl.addEventListener('dragover', function (e) {
        e.preventDefault()
      })
      canvasEl.addEventListener('drop', function (e) {
        e.preventDefault()
        var files = e.dataTransfer.files
        var len = files.length

        // 加载图片
        function loadImage (i) {
          if (i === len) {
            me.run()
          } else {
            var imageItem = {}
            var file = files[i]
            imageItem.src = window.URL.createObjectURL(file)
            imageItem.name = file.name.match(/^(.+)\.(?:png|jpe?g|svg)$/i)[1]
            imageItem.img = new Image()
            imageItem.img.src = imageItem.src
            imageItem.img.onload = function () {
              imageItem.w = imageItem.img.width
              imageItem.h = imageItem.img.height
              imageList.push(imageItem)
              loadImage(i + 1)
            }
          }
        }

        // 加载第一张
        loadImage(0)
      })

      // 选择排列形式
      var labels = document.querySelectorAll('[name="type"]')
      for (var i = 0; i < labels.length; i++) {
        labels[i].onclick = function () {
          me.config.dir = this.value
        }
      }

      // 保存雪碧图
      document.querySelector('#btn_save').onclick = function () {
        me.saveSprity()
      }
    },

    /**
     * @description 运行
     */
    run () {
      this.renderImages()
      this.outputStyle()
    },

    /**
     * @description 渲染图片
     */
    renderImages () {
      var config = this.config // 配置对象
      var imageList = this.imageList // 图片数组
      var canvasEl = this.canvasEl // 画布元素
      var ctx = this.ctx // 画图对象
      var x = 0
      var y = 0 // 坐标值

      /* ***计算宽高*** */
      var maxWidth = 0
      var maxHeight = 0
      var totalWidth = 0
      var totalHeight = 0
      imageList.forEach(function (item, index) {
        var image = item.img
        var width = image.width
        var height = image.height

        // 单个最大宽度与最大高度
        maxWidth = maxWidth < width ? width : maxWidth
        maxHeight = maxHeight < height ? height : maxHeight

        // 宽、高总和
        totalWidth += width + config.gapWidth
        totalHeight += height + config.gapWidth
      })

      // 最小值设置
      maxWidth = maxWidth < 5 ? 5 : maxWidth
      maxHeight = maxHeight < 5 ? 5 : maxHeight
      totalWidth = totalWidth < 5 ? 5 : totalWidth
      totalHeight = totalHeight < 5 ? 5 : totalHeight

      // 竖向排列
      if (config.dir === 'vertical') {
        // 设置画布宽高
        canvasEl.width = maxWidth
        canvasEl.height = totalHeight

        // 遍历画图
        imageList.forEach(function (item, index) {
          var image = item.img
          var width = image.width
          var height = image.height

          // 坐标
          item.x = 0
          item.y = 0 - y

          // y轴记录
          y += height + config.gapWidth

          // 画图
          ctx.drawImage(image, 0, 0 - item.y, width, height)
          // console.log(image)
        })
      } else if (config.dir === 'horizon') {
        // 水平排列
        // 设置画布宽高
        canvasEl.width = totalWidth
        canvasEl.height = maxHeight

        // 遍历画图
        imageList.forEach(function (item, index) {
          var image = item.img
          var width = image.width
          var height = image.height

          // 坐标
          item.y = 0
          item.x = 0 - x

          // y轴记录
          x += width + config.gapWidth

          // 画图
          ctx.drawImage(image, 0 - item.x, 0, width, height)
          // console.log(image);
        })
      } else if (config.dir === 'tree') {
        // 树状排列
        imageList.forEach(function (item, index) {
          var image = item.img
          var width = image.width
          var height = image.height
          y += width
          item.y = 0
          item.x = y - width
          ctx.drawImage(image, item.x, 0, width, height)
        })
      }
    },

    /**
     * @description 输出样式
     */
    outputStyle () {
      var imageList = this.imageList // 图片数组
      var css1 = []
      var css2 = []
      var css3 = []
      var less1 = []
      var less2 = []
      var less3 = []

      // 遍历图片，生成样式
      imageList.forEach(function (item, index) {
        var itemName = '.' + item.name

        css1.push(
          itemName + ' {\n',
          '\twidth:' + item.w + 'px;\n',
          '\theight:' + item.h + 'px;\n',
          '\tbackground-position:' + item.x + 'px ' + item.y + 'px;\n',
          '}\n'
        )

        css2.push(
          itemName + ':before {\n',
          '\twidth:' + item.w + 'px;\n',
          '\theight:' + item.h + 'px;\n',
          '\tbackground-position:' + item.x + 'px ' + item.y + 'px;\n',
          '}\n'
        )

        css3.push(
          itemName + ':before {\n',
          '\tcontent:"";\n',
          '\tdisplay:inline-block;\n',
          '\tvertical-align:middle;\n',
          '\twidth:' + item.w + 'px;\n',
          '\theight:' + item.h + 'px;\n',
          '\tbackground-position:' + item.x + 'px ' + item.y + 'px;\n',
          '}\n'
        )

        /* ***less*** */
        less1.push(
          itemName + ' () {\n',
          '\twidth:' + item.w + 'px;\n',
          '\theight:' + item.h + 'px;\n',
          '\tbackground-position:' + item.x + 'px ' + item.y + 'px;\n',
          '}\n'
        )

        less2.push(
          itemName + ' () {\n',
          '\t&:before {\n',
          '\t\twidth:' + item.w + 'px;\n',
          '\t\theight:' + item.h + 'px;\n',
          '\t\tbackground-position:' + item.x + 'px ' + item.y + 'px;\n',
          '\t}\n',
          '}\n'
        )

        less3.push(
          itemName + ' () {\n',
          '\t&:before {\n',
          '\t\tcontent:"";\n',
          '\t\tdisplay:inline-block;\n',
          '\t\tvertical-align:middle;\n',
          '\t\twidth:' + item.w + 'px;\n',
          '\t\theight:' + item.h + 'px;\n',
          '\t\tbackground-position:' + item.x + 'px ' + item.y + 'px;\n',
          '\t}\n',
          '}\n'
        )
      })

      // 输出合并样式
      document.querySelector('.css-1').value = css1.join('')
      document.querySelector('.css-2').value = css2.join('')
      document.querySelector('.css-3').value = css3.join('')
      document.querySelector('.less-1').value = less1.join('')
      document.querySelector('.less-2').value = less2.join('')
      document.querySelector('.less-3').value = less3.join('')

      // 公用样式
      var css0 = []
      css0.push(
        '.ico {\n',
        '\tdisplay:inline-block;\n',
        '\tvertical-align:middle;\n',
        '}\n'
      )
      css0.push(
        '.ico:before {\n',
        '\tcontent:"";\n',
        '\tdisplay:inline-block;\n',
        '\tvertical-align:middle;\n',
        '}\n'
      )
      document.querySelector('.css-0').value = css0.join('')

      var less0 = []
      less0.push(
        '.ico () {\n',
        '\tdisplay:inline-block;\n',
        '\tvertical-align:middle;\n',
        '}\n'
      )
      less0.push(
        '.ico () {\n',
        '\t&:before {\n',
        '\t\tcontent:"";\n',
        '\t\tdisplay:inline-block;\n',
        '\t\tvertical-align:middle;\n',
        '\t}\n',
        '}\n'
      )
      document.querySelector('.less-0').value = less0.join('')
    },

    /**
     * @description 保存雪碧图
     */
    saveSprity () {
      imager.downloadFile('ico-merge.png', this.canvasEl.toDataURL('image/png'))
    }
  },

  mounted () {
    this.init()
  }
}
</script>

<style lang="less">
.container-canvas {
  min-height: 600px;
  background: #efefef;
}
</style>
